package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.PayAndBackAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseArrayDialogFragment;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.PayAndBackParams;
import com.isunland.managesystem.entity.PayMoneyLog;
import com.isunland.managesystem.entity.PayMoneyLogListOriginal;
import com.isunland.managesystem.entity.PayWay;
import com.isunland.managesystem.entity.TencentPay;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.OrderInfoUtil2_0;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.PayResult;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.JSONException;

/**
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2016/12/12 19:50
 */

public class PayAndBackFragment extends BaseListFragment {
  /**
   * 支付宝账户登录授权业务：入参pid值
   */
  //public static final String PID = "2088521417483696";
  /**
   * 支付宝账户登录授权业务：入参target_id值
   */
  //public static final String TARGET_ID = "isunland2016@163.com";
  /**
   * 支付宝支付业务：入参app_id
   */
  public static final String ALIPAY_APPID = "2016120904052627";

  /**
   * 支付宝.商户私钥，pkcs8格式
   */
  public static final String ALIPAY_RSA_PRIVATE =
      "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM3NBtbuCR4FJsZJjDyHTP4w2RDTA1OuDHjIQmS6Y4DM5zAxaBqumSJ2dQt36wnWUnBC5rD9oCvptnMEKB9/+yFopCGyL0NDpn67eg513jxWHrztHy5QeZwdeF2d/PpfmOp061o5/HgirD+i6M1/J/jzkl7QWRSuipzpAeS3m0HrAgMBAAECgYBLuGEI2YIPQpP2pv7rElkYuX5UO19g/YvnML+E8jNEI5/4UmVcU9tSG8WK169p6ipg1ayteFPjdFVF0kS0+lC6W9eCPvm42xD+xoQkog6WkYxNgI33mPD4mAUDjbNUaq7jxi6e09TeXgBqoj7L9dUM7g7H26zmtGjxsvhqt4doQQJBAPSbax1gZ4E5fF2pjpwaitz01eJ40G42KCWtFk4mBt2zea5Ryg+MAwmQDD4dkID6NQUnTXXX+hTdsICt+HFYdgsCQQDXYuamAeUE+73XSpbzTkmQ/97bj1ZpIbqO7/FG/0hgg5/L2dYf+XartSNNbAlLKQL41hW2Ty4kbbihgg5FBy+hAkEAyD+EDWSi17PMEJGC4mEIVaNKhkEJwXAspctxe0C+Vjlb4E2s8dVZlzaKDz/80NoFFdb7HwJVBUgH+xBxV7lnyQJAVmDwlUUPPudi5DOixCLyd/dVvgIHKpR/SBHMVqfMtAA1lsBfEmWuhQBZDxSzyXPCIF9jR8ELhUqHkCYjaOWP4QJAGjG7e+DkqEkmMq9szBY2I0iwsKcf0UAYY6inakQOV1Cbu64gNX3AfcWcp3TeBcdo4m7XjSbFUznozHjxhS2N7g==";
  //public static final String EXTRA_ID =
  //    "com.isunland.intelligentFarmbyWJ.ui.SettlementInfolFragment.EXTRA_ITEM";
  //public static final String EXTRA_MONEY = PayAndBackFragment.class.getSimpleName() + "EXTRA_MONEY";
  //public static final int TYPE_DEFAULT = 0;
  //public static final int TYPE_DETAIL = 1;
  // public static final int TYPE_PAGER = 2;
  /** 选择支付方式 */
  private static final int REQUEST_PAY_WAY = 1;
  private static final int SDK_PAY_FLAG = 2;
  private static final int REQUEST_PAY_KIND = 3;

  @BindView(R.id.tv_settlementWay) TextView tvSettlementWay;
  @BindView(R.id.et_settlementMoney) EditText mEtSettlementMoney;
  @SuppressWarnings("all") @BindView(R.id.btn_nextStep) Button btnNextStep;
  @BindView(R.id.tv_hasSettlement_settlementInfo) TextView mTvHasSettlementSettlementInfo;

  private FragmentManager mFm;
  private ArrayList<PayWay> mPayWayList;
  private PayWay mPayWay = new PayWay();
  @SuppressLint("HandlerLeak") private Handler mHandler = new MyHandler();
  private IWXAPI mWechatPayApi;
  private PayAndBackAdapter<PayMoneyLog> mAdapter;
  private ArrayList<PayMoneyLog> mList;
  private PayAndBackParams mParams;
  private BroadcastReceiver mWeChatPayReceiver = new BroadcastReceiver() {
    @Override public void onReceive(Context context, Intent intent) {
      int result = intent.getIntExtra(WXPayEntryActivity.EXTRA_ERRCODE, -1);
      ToastUtil.show("result=" + result);
      //noinspection StatementWithEmptyBody
      if (result == WXPayEntryActivity.VALUE_SUCCESS) {
        //本地支付成功,查询接口是否支付成功.
        //volleyPostWeChatPayResult();
      }
    }
  };
  /** 是否使用微信支付,为true时,查询支付结果 */
  private boolean mIsWeChatPay;
  /** 微信流水号,用于查询是否支付成功,与生成订单是同一个 */
  private String mWeChatOrderNo;

  @Override public void onResume() {
    super.onResume();
    if (mIsWeChatPay) {
      mIsWeChatPay = false;
      volleyPostWeChatPayResult();
    }
  }

  private void volleyPostWeChatPayResult() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_DETAIL_WECHAT_PAY_RESULT);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mParams.getId());
    params.put("mainId", mParams.getMainId());
    params.put("payWay", mPayWay.getCode());//支付方式.
    //noinspection deprecation
    params.put("payTime", MyDateUtil.parseTimeToString(new Date()));
    params.put("payMuch",
        mParams.isEditable() ? mEtSettlementMoney.getText().toString() : mParams.getPayMuch());
    params.put("operationWay", "1");
    params.put("moneyType", mParams.getMoneyType());
    params.put("orderType", mParams.getOrderType());
    params.put("bookOrderNo", mParams.getBookOrderNo());
    params.put("payMuchTotal", MyStringUtil.getText(mEtSettlementMoney));
    params.put("onlineOrderNO", mWeChatOrderNo);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failPay);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base response = new Gson().fromJson(arg0, Base.class);
        ToastUtil.show(response.getMessage());
        if (response.getResult() == 1) {
          mActivity.setResult(Activity.RESULT_OK);
          volleyPost();//更新列表
          //详情页面要回到列表
          if (PayAndBackParams.TYPE_DETAIL.equalsIgnoreCase(mParams.getPageType())) {
            mActivity.finish();
          }
        }
      }
    });
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    IntentFilter filter = new IntentFilter(WXPayEntryActivity.ACTION_SHOW_NOTIFICATION);
    mActivity.registerReceiver(mWeChatPayReceiver, filter, WXPayEntryActivity.PERM_PRIVATE, null);
  }

  @Override public void initData() {
    super.initData();
    if (mBaseParams != null && mBaseParams instanceof PayAndBackParams) {
      mParams = (PayAndBackParams) mBaseParams;
    }
    if (mParams == null) mParams = new PayAndBackParams();
    mFm = getActivity().getSupportFragmentManager();
    mPayWayList = new ArrayList<>();
    mPayWayList.add(new PayWay(getString(R.string.weChat), PayWay.WE_CHAT_PAY));
    mPayWayList.add(new PayWay(getString(R.string.aliPay), PayWay.ALIPAY));
    //预约订单去掉现金和其他方式
    if (!MyStringUtil.equals(PayAndBackParams.ORDER_TYPE_ORDER, mParams.getOrderType())) {
      mPayWayList.add(new PayWay(getString(R.string.cash), PayWay.CASH));
      mPayWayList.add(new PayWay(getString(R.string.otherPayWay), PayWay.OTHER));
    }
    //注册到微信.
    mWechatPayApi =
        WXAPIFactory.createWXAPI(getActivity(), WXPayEntryActivity.WECHATPAY_APPID, true);
    mWechatPayApi.registerApp(WXPayEntryActivity.WECHATPAY_APPID);
    mList = new ArrayList<>();
    mAdapter = new PayAndBackAdapter<>(mActivity, mList);
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(mParams.getTitle());
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_settlement_info, mListview,
            false);
    ButterKnife.bind(this, header);
    mEtSettlementMoney.setText(String.valueOf(
        MyStringUtil.getTotalDouble(mParams.getPayMuch(), getString(R.string.comma))));
    mEtSettlementMoney.setEnabled(mParams.isEditable());
    mListview.addHeaderView(header);
    setListAdapter(mAdapter);
  }

  @Override public String getUrl() {
    return ApiConst.URL_GET_LIST_PAY_AND_BACK;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainId", mParams.getMainId());
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    //测试json数据.放在文件中.
    //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testHasSettlementList.json");
/**/
    PayMoneyLogListOriginal result = new Gson().fromJson(json, PayMoneyLogListOriginal.class);
    if (result.getResult() == Base.SUCCESS && result.getRows() != null) {
      //获取列表成功
      mList.clear();
      mList.addAll(result.getRows());
      mAdapter.notifyDataSetChanged();
      double cost = getTotalCost(result.getRows());
      String costStr = getString(R.string.hasSettlementWithPlaceHolder, String.valueOf(cost));
      mTvHasSettlementSettlementInfo.setText(costStr);
    }
  }

  @OnClick({ R.id.btn_nextStep, R.id.tv_settlementWay }) public void onClick(View view) {
    if (view == null) return;
    switch (view.getId()) {
      case R.id.btn_nextStep://下一步
        double money =
            MyStringUtil.valueOfDouble(mEtSettlementMoney.getText().toString().trim(), 0);
        if ((money > 10000000) || (money < 0.01)) {
          ToastUtil.show("请输入合理的金额!");
          return;
        }
        showPayInfo(mPayWay, MyStringUtil.getText(mEtSettlementMoney));
        break;
      case R.id.tv_settlementWay://选择支付方式

        BaseArrayDialogFragment dialog = PayWayDialogFragment.newInstance(mPayWayList);
        if (dialog == null) break;
        dialog.setTargetFragment(this, REQUEST_PAY_WAY);
        dialog.show(mFm, "");
        break;
    }
  }

  /**
   * 支付,调用前需要进行有效性判断.
   */
  private void showPayInfo(PayWay payway, String moneyStr) {
    if (payway == null) {
      ToastUtil.show("请选择支付方式!");
      return;
    }
    if (MyStringUtil.isEmptyTextView(tvSettlementWay)) {
      ToastUtil.show("请选择支付方式!");
      return;
    }

    if (MyStringUtil.isEmpty(moneyStr)) {
      ToastUtil.show("请输入金额!");
    }
    //验证金额有效性
    double money = MyStringUtil.valueOfDouble(moneyStr, 0);
    if (money == 0) {
      ToastUtil.show("请输入正确的金额!");
      return;
    }
    String infoStr =
        MyStringUtil.connect(payway.getName(), getString(R.string.colon), String.valueOf(money),
            getString(R.string.yuan));

    BaseConfirmDialogFragment dialog =
        BaseConfirmDialogFragment.newInstance(infoStr, R.string.confirmMoney);
    dialog.setTargetFragment(this, REQUEST_PAY_KIND);
    dialog.show(mFm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_PAY_WAY && data != null) {
      mPayWay = (PayWay) data.getSerializableExtra(BaseArrayDialogFragment.EXTRA_VALUE);
      tvSettlementWay.setText(mPayWay.getName());
    }
    if (requestCode == REQUEST_PAY_KIND) {
      //微信支付不是作业任务时,调用微信接口,否则.现金付款成功,调用接口
      if ((!MyStringUtil.equals(mParams.getOrderType(), PayAndBackParams.ORDER_TYPE_LOCALE_WORK))
          && MyStringUtil.equals(mPayWay.getCode(), PayWay.WE_CHAT_PAY)) {
        volleyPostWeChatPrePay();
        //startActivity(new Intent(mActivity,TestActivity.class));
      } else {
        volleyPostUpdatePayInfo();
      }
    }
  }

  private void volleyPostUpdatePayInfo() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PAY_UPDATE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mParams.getId());
    params.put("mainId", mParams.getMainId());
    params.put("payWay", mPayWay.getCode());//支付方式.
    //noinspection deprecation
    params.put("payTime", MyDateUtil.parseTimeToString(new Date()));
    params.put("payMuch",
        mParams.isEditable() ? mEtSettlementMoney.getText().toString() : mParams.getPayMuch());
    params.put("operationWay", "1");
    params.put("moneyType", mParams.getMoneyType());
    params.put("orderType", mParams.getOrderType());
    params.put("bookOrderNo", mParams.getBookOrderNo());
    params.put("payMuchTotal", MyStringUtil.getText(mEtSettlementMoney));
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failPay);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base response = new Gson().fromJson(arg0, Base.class);
        ToastUtil.show(response.getMessage());
        if (response.getResult() == 1) {
          mActivity.setResult(Activity.RESULT_OK);
          volleyPost();//更新列表
          //详情页面要回到列表
          if (PayAndBackParams.TYPE_DETAIL.equalsIgnoreCase(mParams.getPageType())) {
            mActivity.finish();
          }
        }
      }
    });
  }

  /**
   * 微信支付
   */
  private void volleyPostWeChatPrePay() {
    mWeChatOrderNo = MyDateUtil.getOrderNo();
    //String url = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_WECHAT_PREPAY);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("body", mParams.getOrderTypeName(mActivity));//商品名（默认模块名称
    params.put("total_fee", MyStringUtil.getText(mEtSettlementMoney));//总金额
    params.put("out_trade_no", mWeChatOrderNo);//流水号.
    MyUtils.showDialogLoading(getActivity(), "获取订单中...");
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

          @Override public void onVolleyError(VolleyError arg0) {
            LogUtil.i("error=" + arg0);
          }

          @Override public void onVolleyResponse(String content) throws JSONException {
            try {
              if (content == null) {
                ToastUtil.show("服务器请求错误");
                return;
              }

              Log.e("get server pay params:", content);
              TencentPay json = new Gson().fromJson(content, TencentPay.class);

              if (!MyStringUtil.equalsIgnoreCase(TencentPay.SUCCESS, json.getResult_code())) {
                ToastUtil.show(MyStringUtil.connect(R.string.generatePrePayOrder, R.string.failure));
                return;
              }

              LinkedHashMap<String, String> params = new LinkedHashMap<>();
              params.put("appid", WXPayEntryActivity.WECHATPAY_APPID);
              params.put("noncestr", json.getNonce_str());
              params.put("package", "Sign=WXPay");
              params.put("partnerid", json.getMch_id());
              params.put("prepayid", json.getPrepay_id());
              params.put("timestamp", MyStringUtil.valueOf(System.currentTimeMillis() / 1000));
              params.put("key", WXPayEntryActivity.WECHATPAY_KEY);
              String signValue = MyStringUtil.joinStr(params, "&");
              //signValue=signValue+"&key="+VALUE_WE_CHAT_KEY;
              PayReq payRequest = new PayReq();
              //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
              payRequest.appId = WXPayEntryActivity.WECHATPAY_APPID;
              payRequest.nonceStr = json.getNonce_str();//随机串.防重发
              payRequest.packageValue = "Sign=WXPay";
              payRequest.partnerId = json.getMch_id();//商户号
              payRequest.prepayId = json.getPrepay_id();
              payRequest.timeStamp = MyStringUtil.valueOf(System.currentTimeMillis() / 1000);
              //noinspection ConstantConditions
              payRequest.sign = MyUtils.getMD5(signValue).toUpperCase();
              //payRequest.extData = "app data"; // optional
              //ToastUtil.show("正常调起支付");
              // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
              //发起支付请求.
              payRequest.checkArgs();
              mWechatPayApi.sendReq(payRequest);
              mIsWeChatPay = true;
            } catch (Exception e) {
              Log.e("PAY_GET", "异常：" + e.getMessage());
              ToastUtil.show("PAY_GET异常：" + e.getMessage());
            }
          }
        }

    );
  }

  /**
   * 支付宝支付业务
   */
  @SuppressWarnings("unused") public void alipay() {

    /**
     * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
     * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
     * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
     *
     * orderInfo的获取必须来自服务端；
     */

    Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(ALIPAY_APPID);
    String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
    String sign = OrderInfoUtil2_0.getSign(params, ALIPAY_RSA_PRIVATE);
    final String orderInfo = orderParam + "&" + sign;

    Runnable payRunnable = new Runnable() {

      @Override public void run() {
        PayTask alipay = new PayTask(getActivity());
        Map<String, String> result = alipay.payV2(orderInfo, true);
        Log.i("msp", result.toString());

        Message msg = new Message();
        msg.what = SDK_PAY_FLAG;
        msg.obj = result;
        mHandler.sendMessage(msg);
      }
    };

    Thread payThread = new Thread(payRunnable);
    payThread.start();
  }

  private double getTotalCost(ArrayList<PayMoneyLog> rows) {
    double totalCost = 0;
    for (PayMoneyLog item : rows) {
      double cost;
      try {
        cost = Double.parseDouble(item.getPayMuch());
      } catch (NumberFormatException e) {
        e.printStackTrace();
        cost = 0;
      }

      if ("1".equals(item.getOperationWay())) {

        totalCost = totalCost + cost;
      } else {
        totalCost = totalCost - cost;
      }
    }
    return totalCost;
  }

  @Override public void onDestroy() {
    super.onDestroy();
    mActivity.unregisterReceiver(mWeChatPayReceiver);
  }

  @Override public void initMockData() {
    super.initMockData();
    mParams.setOrderType(PayAndBackParams.ORDER_TYPE_ORDER);
    mParams.setPayMuch("1");
    initData();
  }

  @SuppressLint("HandlerLeak") private class MyHandler extends Handler {

    @SuppressWarnings("unused") public void handleMessage(Message msg) {
      switch (msg.what) {
        case SDK_PAY_FLAG: {
          @SuppressWarnings("unchecked") PayResult payResult =
              new PayResult((Map<String, String>) msg.obj);
          /**
           对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
           */
          String resultInfo = payResult.getResult();// 同步返回需要验证的信息
          String resultStatus = payResult.getResultStatus();
          // 判断resultStatus 为9000则代表支付成功
          if (TextUtils.equals(resultStatus, "9000")) {
            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
            ToastUtil.show("支付成功");
          } else {
            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
            ToastUtil.show("支付失败");
          }
          break;
        }

        default:
          break;
      }
    }
  }
}
